import { defineStore } from 'pinia';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

export const useUserStore = defineStore('user', {
    state: () => ({
        token: localStorage.getItem('token') || '',
        userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {},
        loginTime: localStorage.getItem('loginTime') || ''
    }),
    actions: {
        setLoginData(data) {
            this.token = data.token;
            this.userInfo = data.userInfo;
            this.loginTime = new Date().toString();
            localStorage.setItem('token', data.token);
            localStorage.setItem('userInfo', JSON.stringify(data.userInfo));
            localStorage.setItem('loginTime', this.loginTime);
            ElMessage.success('登录成功');
        },
        logout() {
            this.token = '';
            this.userInfo = {};
            this.loginTime = '';
            localStorage.clear();
            useRouter().push('/login');
            ElMessage.info('已退出登录');
        }
    }
});